import 'dart:async';

import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/services/api.dart';
import 'package:yp/utils/util.dart';

import 'group_detail_state.dart';
import 'package:yp/pages/address_selector/address_model.dart';

class Group_detailLogic extends GetxController {
  final Group_detailState state = Group_detailState();


  @override
  void onReady() {
    print(Get.arguments);
    if (Get.arguments != null) {
     state.arguments = Get.arguments;
    } else {
      var gbuyid = getQueryVariable('g_buy_id');
      state.arguments['g_buy_id'] = gbuyid;
    }

    getCurrentLocationInfo(success: (backInfo){
      if (backInfo != null) {
        state.addressAllString = backInfo["addressAllString"];
        state.addressInfo = backInfo["addressInfo"];

        getshopInfo(null);
        getcodelistget();
      }
    });
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onClose() {
    state.timer.cancel();
    super.onClose();
    print('SimpleController--onClose');
  }

  //获取商品信息
  getshopInfo(norm_num_id) {
    print('拼团详情+++++++++++++++++');
    var shop_id = state.arguments['shop_id']??102002001;
    /// 获取订单详情
    /// "data_sign":0,"channel_num_id":98,"use_platform":3,"tml_num_id":"","g_buy_id":"21101400010001","shop_id":102002001,"prv_num_id":"320000","city_num_id":"320300","city_area_num_id":"320303","access_token":"8e655f04ae3340339666dce3d3995615","usr_num_id":430
    var params = {
      "data_sign": 0,
      "channel_num_id": 99,
      "use_platform": 3,
      "tml_num_id": "",
      "g_buy_id": state.arguments['g_buy_id'],
      // "shop_id": SpUtil.getInt('storeShopNum'),
      "shop_id": shop_id,

      "prv_num_id": state.addressInfo["prv_num_id"],
      "city_num_id": state.addressInfo["city_num_id"],
      "city_area_num_id": state.addressInfo["city_area_num_id"],
      "town_num_id": state.addressInfo["town_num_id"],
      "maplocation_x": state.addressInfo["maplocation_x"],
      "maplocation_y": state.addressInfo["maplocation_y"],
      "adr_num_id": state.addressInfo["adr_num_id"],
      "range_type": "1", // 拼团：1：判断是否在配送范围，不传默认不判断；

      'norm_num_id': norm_num_id == null ? '' : norm_num_id,
      // "access_token": SpUtil.getString('token'),
    };
    print("state.group_buy_item.runtimeType.toString()");
    print(params);
    Api.groupDetail(params).listen((event) {
      if (event['code'] == 0) {
        if (event['group_buy_item'] != null) {
          state.buy_item_norms = event['buy_item_norms'];
          state.click_buy_item_norms = state.buy_item_norms[0];
          state.group_buy_item = event['group_buy_item'];
          state.buy_item_norms.forEach((element) {
            if (element['g_buy_norm_num_id'] == state.group_buy_item['g_buy_norm_num_id']) {
              element['isSelect'] = true;
            } else {
              element['isSelect'] = false;
            }
          });

          state.deliveryType = 1;
          if (event["group_buy_item"] != null) {
            if (event["group_buy_item"]["delivery_type"] != null) {
              state.deliveryType = event["group_buy_item"]["delivery_type"];
            }
          }

          var _strtimes = DateTime.parse(state.group_buy_item['end_time']); //首先先将字符串格式的时间转为DateTime类型，因为millisecondsSinceEpoch方法转换要求为该格式
          var _intendtime = _strtimes.millisecondsSinceEpoch; //方法一
          state.seconds = _intendtime ~/ 1000 - DateTime.now().millisecondsSinceEpoch ~/ 1000;
          print('state.seconds');
          print(state.seconds);

          // state.seconds = state.group_buy_item['distance_time'] / 1000.floor();
          List imgArr = [];
          imgArr = state.group_buy_item['image_url'].split(',');

          imgArr.forEach((element) {
            state.imageList.add({'logo': element});
          });
          print(imgArr);
          startTimer();
        }
      }
      update();
    });
  }

  getcodelistget() {
    var params1 = {"channel_num_id": 99, "use_platform": 3, "current_page": 1, "page_size": 40, "g_buy_id": state.arguments['g_buy_id'], "tml_num_id": ""};
    Api.codelistget(params1).listen((event) {
      if (event['code'] == 0) {
        if (event['codes'] != null && event['codes'].length > 0) {
          state.codes = [];
          event['codes'].forEach((element) {
            if (element['g_buy_size'] - element['g_buy_join_size'] > 0) {
              state.codes.add(element);
            }
          });
        }
      }
      update();
    });
  }

  date_format(micro_second) {
// 总秒数
    var second = (micro_second).floor();
// 天数
    var day = (second / 3600 / 24).floor();
// 小时
    var hr = (second / 3600 % 24).floor();
// 分钟
    var min = (second / 60 % 60).floor();
// 秒
    var secs = (second % 60).floor();

    return day.toString() + "天" + hr.toString() + "小时" + min.toString() + "分钟" + secs.toString() + "秒";
  }

  //时间格式化，根据总秒数转换为对应的 hh:mm:ss 格式
  static String constructTime(double mss) {
    int days = (mss / (60 * 60 * 24)).floor();
    int hours = ((mss % (60 * 60 * 24)) / (60 * 60)).floor();
    int minutes = ((mss % (60 * 60)) / 60).floor();
    int seconds = (mss % 60).floor();
    return days.toString() + "天" + hours.toString() + "小时" + minutes.toString() + "分钟" + seconds.toString() + "秒";
  }

  static String constructVipTime(int seconds) {
    int day = seconds % 1000 ~/ 3600 ~/ 24;
    int hour = seconds % 1000 ~/ 3600;
    int minute = seconds % 1000 % 3600 ~/ 60;
    int second = seconds % 1000 % 60;
    // if(day!= 0){
    //   return '剩$day天$hour小时$minute分';
    // }else if(hour!= 0){
    //   return '剩$hour小时$minute分';
    // }else if(minute!=0){
    //   return '剩$minute分';
    // }else {
    //   return '';
    // }
    return formatTime(day) + '天' + formatTime(hour) + "小时" + formatTime(minute) + "分" + formatTime(second);
  }

  //数字格式化，将 0~9 的时间转换为 00~09
  static String formatTime(int timeNum) {
    return timeNum < 10 ? "0" + timeNum.toString() : timeNum.toString();
  }

  void startTimer() {
    const period = const Duration(seconds: 1);
    state.timer = Timer.periodic(period, (timer) {
      if (state.seconds <= 0) {
        //倒计时秒数为0，取消定时器
        print('我被取消了');
        state.timer.cancel();
        // getData();
      }
      state.countContent = date_format(state.seconds);
      state.seconds--;
      update();
    });
    //设置 1 秒回调一次
    // const period = const Duration(seconds: 1);
    // state.timer = Timer.periodic(period, (timer) {
    //   if (state.seconds <= 0) {
    //     //倒计时秒数为0，取消定时器
    //     print('我被取消了  ');
    //     cancelTimer();
    //     // getData();
    //   }
    //   //更新界面
    //   //秒数减一，因为一秒回调一次
    //   state.seconds--;
    //
    //   state.countContent = constructTime(state.seconds);
    //
    //   update();
    // });
  }

  void cancelTimer() {
    if (state.timer != null) {
      state.timer.cancel();
      state.timer = null;
    }
  }
}
